<?php


namespace App\Command;


use EasySwoole\Command\AbstractInterface\CommandHelpInterface;
use EasySwoole\Component\Csp;
use EasySwoole\EasySwoole\Command\CommandInterface;
use EasySwoole\EasySwoole\Core;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\Mysqli\QueryBuilder;
use EasySwoole\ORM\AbstractModel;
use EasySwoole\ORM\DbManager;
use EasySwoole\Utility\File;
use Swoole\Coroutine\Scheduler;
use Swoole\Timer;

class CreateTable implements CommandInterface
{
    public function commandName(): string
    {
        // TODO: Implement commandName() method.
        return 'createTable';
    }

    public function exec(): ?string
    {
        // TODO: Implement exec() method.
        Core::getInstance()->initialize();

        $scheduler = new Scheduler();
        $scheduler->add(function () {
            // 获取model目录下所有文件
            $files = File::scanDirectory(EASYSWOOLE_ROOT . '/App/Model')['files'];

            $builder = new QueryBuilder();

            // 获取当前数据库中所有表名
            $builder->raw("show tables;");
            $tablesArray = DbManager::getInstance()->query($builder, true)->getResult();

            // 将所有表名解析到数组中
            $tables = [];
            if (!empty($tablesArray)) {
                $tables = array_column($tablesArray, key($tablesArray[0]));
            }
            $csp = new Csp();
            foreach ($files as $file) {
                // 将文件解析过滤得到php类文件
                $fileDir = str_replace(EASYSWOOLE_ROOT . '/', '', $file);
                $phpFile = str_replace('.php', '', $fileDir);
                $class = str_replace('/', '\\', $phpFile);

                if (!class_exists($class)) {
                    continue;
                }
                $model = new $class();
                // 判断该类是否是model类
                if ($model instanceof AbstractModel) {
                    // 获取该model表名
                    $tableName = $model->getTableName();
                    // 判断当前数据库是否存在这个表名
                    if (in_array($tableName, $tables) || !method_exists($model, 'schemaInfo')) {
                        continue;
                    }
                    // 获取该表的结构
                    $ddl = $model->schemaInfo()->__createDDL();
                    $csp->add("{$tableName}_table", function () use ($tableName, $ddl) {
                        $builder = new QueryBuilder();
                        $builder->raw($ddl);

                        // 执行sql语句
                        $result = DbManager::getInstance()->query($builder, true)->getResult();
                        if (!$result) {
                            Logger::getInstance()->waring($tableName . '表创建失败！');
                        }
                        return $result;
                    });
                }
            }

            $csp->exec();
            Timer::clearAll();
        });
        $scheduler->start();

        // 清除全部定时器
        Timer::clearAll();

        return 'success';
    }

    public function help(CommandHelpInterface $commandHelp): CommandHelpInterface
    {
        // TODO: Implement help() method.
        // 添加 自定义action(action 名称及描述)
        $commandHelp->addAction('', '自动创建表');
        // $commandHelp->addAction('echo_date', 'print the date');
        // $commandHelp->addAction('echo_logo', 'print the logo');
        // 添加 自定义action 可选参数
        // $commandHelp->addActionOpt('--str=str_value', 'the string to be printed ');
        return $commandHelp;
    }

    public function desc(): string
    {
        // TODO: Implement desc() method.
        return '自动创建表';
    }
}